<?php
/*
Plugin Name: URL Rewrite for Custom Type
Plugin URI: http://www.giuseppetrisciuoglio.it
Description: Questo plugin gestisce le url per i custom types
Author: Giuseppe Trisciuoglio
Version: 1.0
*/

add_action('init', 'gt_rewrite_rules');

function gt_rewrite_rules()
{
	global $wp_rewrite;
	$wp_rewrite->add_rewrite_tag( '%artista-name%', '([^&]+)', 'artistaname=');
}

add_filter('post_type_link', 'gt_permalink');
function gt_permalink($permalink, $post, $leavename)
{
	if ( false !== strpos( $permalink, '%publication-type%/%artista-name%.html' ) ) {

		$publicationtype = get_the_terms($post->ID, 'publication-type');
		$pubyear = date('Y', get_post_meta($post->ID, 'publication_date', true));

		$rewritecode = array(
			'%publication-type%',
			'%pubyear%',
			'%pubmonth%',
			$leavename? '' : '%postname%',
		);

		$rewritereplace = array(
			array_pop($publicationtype)->slug,
			$pubyear,
			$pubmonth,
			$post->post_name
		);

		$permalink = str_replace($rewritecode, $rewritereplace, $permalink);    
    }
    return $permalink;
}

?>